<template>
	<view class="history-page">
		<!-- 顶部导航栏 -->
		<view class="navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-left" @click="goBack">
				<view class="back-icon">
					<text class="fa fa-arrow-left"></text>
				</view>
			</view>
			<view class="navbar-title">
				<text>{{ t('menu.history') }}</text>
			</view>
			<view class="navbar-right">
				<!-- 保留一个空白的区域以平衡布局 -->
			</view>
		</view>
		
		<!-- 聊天记录列表 -->
		<scroll-view class="chat-list" scroll-y="true" @scrolltolower="loadMoreChats" refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing">
			<view v-if="chatList.length === 0 && !isLoading" class="empty-chat-list">
				<view class="empty-content">
					<view class="empty-icon">
						<text class="fa fa-comment-dots"></text>
					</view>
					<text class="empty-text">{{ t('history.noRecords') }}</text>
				</view>
			</view>
			
			<view v-if="isLoading && chatList.length === 0" class="loading-container">
				<view class="loading-spinner">
					<view class="loading-dot" v-for="i in 3" :key="i"></view>
				</view>
				<text class="loading-text">{{ t('common.loading') }}</text>
			</view>
			
			<view v-for="chat in chatList" :key="chat.conversationId" class="chat-item" 
				hover-class="chat-item-hover" @click="openChat(chat.conversationId)">
				<view class="chat-item-content">
					<text class="chat-item-title">{{ chat.title || t('history.newChat') }}</text>
					<text class="chat-item-preview">{{ chat.lastMessage || t('history.startNewChat') }}</text>
					<text class="chat-item-time">{{ getFormattedTime(chat.updateTime) }}</text>
				</view>
				<view class="delete-btn" hover-class="delete-btn-hover" @click.stop="confirmDelete(chat.conversationId)">
					<text class="fa fa-trash-alt"></text>
				</view>
			</view>
			
			<!-- 加载更多指示器 -->
			<view v-if="chatList.length > 0 && isLoadingMore" class="loading-more">
				<view class="loading-dot"></view>
				<view class="loading-dot"></view>
				<view class="loading-dot"></view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { ref, onMounted, onBeforeUnmount } from 'vue';
	// 导入语言包
	import zhLocale from '../../locales/zh.js'
	import enLocale from '../../locales/en.js'
	
	// API基础URL
	const apiBaseUrl = 'http://localhost:8080'; // 替换为你的实际API地址
	
	// 状态栏高度
	const statusBarHeight = ref(20);
	
	// 聊天记录列表
	const chatList = ref([]);
	
	// 分页参数
	const pageParams = ref({
		pageNum: 1,
		pageSize: 10,
		hasMore: true
	});
	
	// 加载状态
	const isLoading = ref(false);
	const isLoadingMore = ref(false);
	const isRefreshing = ref(false);
	
	// 当前语言
	const currentLang = ref('zh'); // 默认中文
	
	// 语言包
	const locales = {
		zh: zhLocale,
		en: enLocale
	};
	
	// 从本地存储获取当前语言设置
	const initLanguage = () => {
		try {
			const savedLang = uni.getStorageSync('appLanguage');
			if (savedLang) {
				currentLang.value = savedLang;
			}
		} catch (e) {
			console.error('获取语言设置失败', e);
		}
	};
	
	// 翻译函数
	const t = (key) => {
		const keys = key.split('.');
		let result = locales[currentLang.value];
		
		for (let k of keys) {
			if (result[k] === undefined) return key;
			result = result[k];
		}
		
		return result;
	};
	
	// 页面加载时
	onMounted(() => {
		// 初始化语言设置
		initLanguage();
		
		// 获取状态栏高度
		try {
			const sysInfo = uni.getSystemInfoSync();
			statusBarHeight.value = sysInfo.statusBarHeight || 20;
		} catch (e) {
			console.error('获取状态栏高度失败', e);
		}
		
		// 从API加载聊天记录
		loadChatList();
	});
	
	// 页面卸载前
	onBeforeUnmount(() => {
		// 可能的清理操作
	});
	
	// 下拉刷新
	const onRefresh = () => {
		isRefreshing.value = true;
		pageParams.value.pageNum = 1;
		pageParams.value.hasMore = true;
		
		loadChatList().then(() => {
			isRefreshing.value = false;
		}).catch(() => {
			isRefreshing.value = false;
		});
	};
	
	// 加载聊天记录
	const loadChatList = () => {
		if (isLoading.value) return Promise.reject('正在加载中');
		
		isLoading.value = true;
		
		// 准备请求参数
		const params = {
			pageNum: pageParams.value.pageNum,
			pageSize: pageParams.value.pageSize,
			userId: 1  // 固定用户ID为1
		};
		
		const queryString = Object.keys(params)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			.join('&');
		
		return new Promise((resolve, reject) => {
			uni.request({
				url: `${apiBaseUrl}/api/conversation/list?${queryString}`,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				},
				success: (res) => {
					if (res.statusCode === 200 && res.data) {
						// 处理会话列表数据
						if (pageParams.value.pageNum === 1) {
							chatList.value = res.data.data || [];
						} else {
							chatList.value = [...chatList.value, ...(res.data.data || [])];
						}
						
						// 判断是否还有更多数据
						if (res.data.total) {
							pageParams.value.hasMore = chatList.value.length < res.data.total;
						} else {
							// 如果后端没有返回total字段，我们假设没有更多数据
							pageParams.value.hasMore = (res.data.data || []).length >= pageParams.value.pageSize;
						}
						
						// 处理每个会话的最后一条消息
						loadLastMessages();
						
						resolve(res.data);
					} else {
						console.error('获取会话列表失败', res);
						uni.showToast({
							title: t('history.fetchFailed'),
							icon: 'none'
						});
						reject(res);
					}
				},
				fail: (err) => {
					console.error('获取会话列表请求失败', err);
					uni.showToast({
						title: t('history.networkError'),
						icon: 'none'
					});
					reject(err);
				},
				complete: () => {
					isLoading.value = false;
				}
			});
		});
	};
	
	// 加载每个会话的最后一条消息
	const loadLastMessages = () => {
		const promises = chatList.value.map(chat => {
			return new Promise((resolve) => {
				uni.request({
					url: `${apiBaseUrl}/api/conversation/${chat.conversationId}/messages`,
					method: 'GET',
					data: {
						pageNum: 1,
						pageSize: 1,
						isDeleted: 0
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.data && res.data.data.data && res.data.data.data.length > 0) {
							const lastMessage = res.data.data.data[0];
							// 更新会话的最后一条消息预览
							chat.lastMessage = truncateText(lastMessage.userQuestion, 30);
						} else {
							chat.lastMessage = t('history.startNewChat');
						}
						resolve();
					},
					fail: () => {
						chat.lastMessage = t('history.startNewChat');
						resolve();
					}
				});
			});
		});
		
		// 等待所有请求完成
		Promise.all(promises).then(() => {
			// 更新UI
			chatList.value = [...chatList.value];
		});
	};
	
	// 加载更多聊天
	const loadMoreChats = () => {
		if (!pageParams.value.hasMore || isLoadingMore.value) return;
		
		isLoadingMore.value = true;
		pageParams.value.pageNum += 1;
		
		// 准备请求参数
		const params = {
			pageNum: pageParams.value.pageNum,
			pageSize: pageParams.value.pageSize
		};
		
		const queryString = Object.keys(params)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			.join('&');
		
		uni.request({
			url: `${apiBaseUrl}/api/conversation/list?${queryString}`,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data) {
					// 处理会话列表数据
					const newChats = res.data.data || [];
					if (newChats.length > 0) {
						chatList.value = [...chatList.value, ...newChats];
						
						// 为新加载的会话加载最后一条消息
						loadLastMessagesForChats(newChats);
					}
					
					// 判断是否还有更多数据
					pageParams.value.hasMore = chatList.value.length < res.data.total;
				} else {
					console.error('加载更多会话失败', res);
				}
			},
			fail: (err) => {
				console.error('加载更多会话请求失败', err);
			},
			complete: () => {
				isLoadingMore.value = false;
			}
		});
	};
	
	// 为指定的会话加载最后一条消息
	const loadLastMessagesForChats = (chats) => {
		const promises = chats.map(chat => {
			return new Promise((resolve) => {
				uni.request({
					url: `${apiBaseUrl}/api/conversation/${chat.conversationId}/messages`,
					method: 'GET',
					data: {
						pageNum: 1,
						pageSize: 1,
						isDeleted: 0
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.data && res.data.data.data && res.data.data.data.length > 0) {
							const lastMessage = res.data.data.data[0];
							// 更新会话的最后一条消息预览
							chat.lastMessage = truncateText(lastMessage.userQuestion, 30);
						} else {
							chat.lastMessage = t('history.startNewChat');
						}
						resolve();
					},
					fail: () => {
						chat.lastMessage = t('history.startNewChat');
						resolve();
					}
				});
			});
		});
		
		// 等待所有请求完成
		Promise.all(promises).then(() => {
			// 更新UI
			chatList.value = [...chatList.value];
		});
	};
	
	// 截取文本
	const truncateText = (text, maxLength) => {
		if (!text) return '';
		text = text.replace(/<[^>]+>/g, ''); // 去除HTML标签
		return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
	};
	
	// 获取格式化的时间
	const getFormattedTime = (timeStr) => {
		if (!timeStr) return '';
		
		const date = new Date(timeStr);
		const now = new Date();
		
		// 判断是否是今天
		if (date.toDateString() === now.toDateString()) {
			// 今天显示时:分
			return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
		}
		
		// 判断是否是昨天
		const yesterday = new Date(now);
		yesterday.setDate(now.getDate() - 1);
		if (date.toDateString() === yesterday.toDateString()) {
			return t('history.yesterday');
		}
		
		// 判断是否是本周
		const daysDiff = Math.floor((now - date) / (1000 * 60 * 60 * 24));
		if (daysDiff < 7) {
			const days = currentLang.value === 'zh' ? 
				['日', '一', '二', '三', '四', '五', '六'] : 
				['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
			return currentLang.value === 'zh' ? 
				'周' + days[date.getDay()] : 
				days[date.getDay()];
		}
		
		// 其他情况返回年-月-日
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	};
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};
	
	// 打开聊天
	const openChat = (conversationId) => {
		// 添加切换中的提示
		uni.showLoading({
			title: t('history.switching'),
			mask: true
		});
		
		// 获取当前页面堆栈
		const pages = getCurrentPages();
		// 查找首页实例
		const indexPage = pages.find(page => page.route === 'pages/index/index');
		
		if (indexPage) {
			// 如果索引页面存在，直接调用其方法
			try {
				indexPage.$vm.switchChat(conversationId);
				console.log('直接调用 switchChat，ID:', conversationId);
			} catch (error) {
				console.error('直接调用 switchChat 失败:', error);
				// 失败时尝试通过事件机制
				uni.$emit('switchChat', { conversationId });
				console.log('通过事件调用 switchChat，ID:', conversationId);
			}
		} else {
			// 如果不存在，通过全局事件通信
			uni.$emit('switchChat', { conversationId });
			console.log('通过事件调用 switchChat，ID:', conversationId);
		}
		
		// 短暂延迟后返回首页
		setTimeout(() => {
			uni.hideLoading();
			uni.navigateBack();
			uni.showToast({
				title: t('history.chatSwitched'),
				icon: 'success',
				duration: 1500
			});
		}, 300);
	};
	
	// 确认删除
	const confirmDelete = (conversationId) => {
		uni.showModal({
			title: t('history.deleteChat'),
			content: t('history.confirmDelete'),
			confirmColor: '#FF3B30',
			success: (res) => {
				if (res.confirm) {
					deleteChat(conversationId);
				}
			}
		});
	};
	
	// 删除聊天
	const deleteChat = (conversationId) => {
		uni.request({
			url: `${apiBaseUrl}/api/conversation/${conversationId}`,
			method: 'DELETE',
			success: (res) => {
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					// 从本地列表中移除
					const index = chatList.value.findIndex(item => item.conversationId === conversationId);
					if (index !== -1) {
						chatList.value.splice(index, 1);
					}
					
					uni.showToast({
						title: t('history.deleted'),
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: t('history.deleteFailed'),
						icon: 'none'
					});
				}
			},
			fail: () => {
				uni.showToast({
					title: t('history.deleteFailed'),
					icon: 'none'
				});
			}
		});
	};
</script>

<style>
	/* 引入Font Awesome图标库 */
	@import url('https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css');
	
	.history-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f7f9fc;
	}
	
	/* 导航栏样式 */
	.navbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 30rpx;
		background: linear-gradient(to right, #4080ff, #5691ff);
		color: white;
		box-shadow: 0 2px 12px rgba(64, 128, 255, 0.2);
		position: relative;
		z-index: 100;
	}
	
	.navbar-left, .navbar-right {
		width: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.navbar-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: 600;
		letter-spacing: 1px;
	}
	
	.back-icon {
		width: 70rpx;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: background-color 0.2s;
	}
	
	.back-icon:active {
		background-color: rgba(255, 255, 255, 0.2);
	}
	
	.fa {
		font-family: 'FontAwesome';
		font-weight: 900;
	}
	
	.fa-arrow-left {
		font-size: 44rpx;
	}
	
	/* 聊天列表样式 */
	.chat-list {
		flex: 1;
		padding: 30rpx;
	}
	
	.chat-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		transition: transform 0.2s, box-shadow 0.2s;
	}
	
	.chat-item-hover {
		transform: scale(0.98);
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
		background-color: #f9f9f9;
	}
	
	.chat-item-content {
		flex: 1;
		padding-right: 20rpx;
	}
	
	.chat-item-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
		margin-bottom: 12rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.chat-item-preview {
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 10rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}
	
	.chat-item-time {
		font-size: 24rpx;
		color: #999999;
		display: block;
	}
	
	.delete-btn {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: background-color 0.2s;
	}
	
	.delete-btn-hover {
		background-color: #ffeef0;
	}
	
	.fa-trash-alt {
		font-size: 38rpx;
		color: #ff3b30;
	}
	
	/* 空状态样式 */
	.empty-chat-list {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80vh;
	}
	
	.empty-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx;
	}
	
	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		background-color: #f0f4ff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 40rpx;
		box-shadow: 0 6px 16px rgba(64, 128, 255, 0.15);
	}
	
	.fa-comment-dots {
		font-size: 100rpx;
		color: #80a9ff;
	}
	
	.empty-text {
		font-size: 34rpx;
		color: #666666;
		margin-bottom: 10rpx;
		text-align: center;
		font-weight: 500;
		letter-spacing: 1px;
	}
	
	/* 加载更多样式 */
	.loading-more {
		display: flex;
		justify-content: center;
		padding: 30rpx;
		align-items: center;
	}
	
	.loading-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 80vh;
	}
	
	.loading-spinner {
		display: flex;
		justify-content: center;
		margin-bottom: 20rpx;
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #666;
	}
	
	.loading-dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #c4d3f7;
		margin: 0 8rpx;
		animation: loading 1.4s infinite ease-in-out both;
	}
	
	.loading-dot:nth-child(1) {
		animation-delay: -0.32s;
	}
	
	.loading-dot:nth-child(2) {
		animation-delay: -0.16s;
	}
	
	@keyframes loading {
		0%, 80%, 100% {
			transform: scale(0);
		}
		40% {
			transform: scale(1);
		}
	}
	
	/* 自定义滚动条样式 */
	::-webkit-scrollbar {
		width: 5px;
	}
	::-webkit-scrollbar-track {
		background: #f1f1f1;
	}
	::-webkit-scrollbar-thumb {
		background: #888;
		border-radius: 5px;
	}
	::-webkit-scrollbar-thumb:hover {
		background: #555;
	}
</style> 